package com.example.back.service;

import com.example.back.entity.Notice;
import com.example.back.entity.ShouCang;
import com.example.back.mapper.NoticeMapper;
import com.example.back.mapper.PostMapper;
import com.example.back.mapper.ShouCangMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;


@Service
public class ShouCangService {
    @Autowired
    private ShouCangMapper shouCangMapper;
    @Autowired
    private NoticeMapper noticeMapper;
    @Autowired
    private PostMapper postMapper;

    public int addShouCang(ShouCang shouCang){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        int result = shouCangMapper.addShouCang(shouCang);
        if (result > 0) {
            int postUserId = postMapper.queryPostById(shouCang.getPostId()).getUserId();
            Notice notice = new Notice();
            notice.setUserId(postUserId);
            notice.setTriggerUserId(shouCang.getUserId());
            notice.setPostId(shouCang.getPostId());
            notice.setTime(sdf.format(new Date()));
            notice.setText("用户 " + shouCang.getUserId() + " 收藏了您的帖子 " + shouCang.getPostId());
            notice.setType("collection");
            noticeMapper.addNotice(notice);
        }
        return result;
    }

    public int deleteShouCangById(Serializable id){
        return shouCangMapper.deleteShouCangById(id);
    }

    public int updateShouCang(ShouCang shouCang){
        return shouCangMapper.updateShouCang(shouCang);
    }

    public ShouCang selectShouCangById(Serializable id){
        return shouCangMapper.selectShouCangById(id);
    }

    public ArrayList<ShouCang> selectShouCang(ShouCang shouCang){
        return shouCangMapper.selectShouCang(shouCang);
    }

    //====================
    public Integer getCollectIdByUserAndPost(Integer userId, Integer postId) {
        return shouCangMapper.selectIdByUserAndPost(userId, postId);
    }

    public boolean isCollected(Integer userId, Integer postId) {
        return shouCangMapper.countByUserAndPost(userId, postId) > 0;
    }
}
